<template>
  <div class="chat-container">
    <h1>家长聊天</h1>

    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} 家长</p>
      <router-link to="/parent/dashboard">返回Dashboard</router-link>
    </div>

    <div class="chat-main">
      <div class="contacts-section">
        <h2>联系人</h2>
        <div class="child-selector" v-if="userProfile.children && userProfile.children.length > 0">
          <label for="child-select">选择孩子:</label>
          <select id="child-select" v-model="selectedChild" @change="loadContacts">
            <option value="">请选择孩子</option>
            <option v-for="child in userProfile.children" :key="child.studentNumber" :value="child">
              {{ child.fullName }}
            </option>
          </select>
          <button @click="loadContacts" class="refresh-btn">刷新联系人</button>
        </div>

        <div class="contacts-list">
          <div
              v-for="contact in contacts"
              :key="contact.userId"
              class="contact-item"
              :class="{ active: activeContact && activeContact.userId === contact.userId }"
              @click="selectContact(contact)"
          >
            <div class="contact-avatar">
              {{ contact.fullName.charAt(0) }}
            </div>
            <div class="contact-info">
             <span v-if="contact.userType === '1' ">
                  {{ contact.subejt }} - {{ contact.fullName }}
                </span>
              <span v-else>
                  {{ contact.fullName }}
                </span>
              <div class="contact-type">{{ getUserTypeText(contact.userType) }}</div>
            </div>
            <div v-if="unreadCounts[contact.userId] && unreadCounts[contact.userId] > 0" class="unread-badge">
              {{ unreadCounts[contact.userId] }}
            </div>
          </div>

          <div v-if="contacts.length === 0 && selectedChild" class="no-contacts">
            暂无联系人
          </div>

          <div v-if="!selectedChild && userProfile.children && userProfile.children.length > 0" class="no-contacts">
            请选择一个孩子查看联系人
          </div>

          <div v-if="!userProfile.children || userProfile.children.length === 0" class="no-contacts">
            您还没有关联的孩子信息
          </div>
        </div>
      </div>

      <div class="chat-section">
        <div v-if="activeContact" class="chat-header">
          <h3>与 {{ activeContact.fullName }} 聊天</h3>
          <button @click="loadChatHistory" class="refresh-btn">刷新</button>
        </div>
        <div v-else class="chat-placeholder">
          <p>请选择一个联系人开始聊天</p>
        </div>

        <div v-if="activeContact" class="chat-messages" ref="messagesContainer">
          <div
              v-for="message in messages"
              :key="message.id"
              class="message"
              :class="{ 'sent': message.senderId === userProfile.userId, 'received': message.senderId !== userProfile.userId }"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ formatDateTime(message.sentAt) }}
            </div>
          </div>
        </div>

        <div v-if="activeContact" class="chat-input">
          <textarea
              v-model="newMessage"
              placeholder="输入消息..."
              @keydown.enter="sendMessage"
          ></textarea>
          <button @click="sendMessage" :disabled="!newMessage.trim()">发送</button>
        </div>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

export default {
  name: 'ParentChat',
  setup() {
    // 用户信息
    const userProfile = ref({});
    const selectedChild = ref(null);

    // 联系人
    const contacts = ref([]);
    const activeContact = ref(null);

    // 消息
    const messages = ref([]);
    const newMessage = ref('');
    const messagesContainer = ref(null);
    const unreadCounts = ref({}); // 未读消息计数

    // 定时器
    let messageRefreshTimer = null;
    let unreadCountTimer = null;

    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 加载联系人
    const loadContacts = async () => {
      if (!selectedChild.value) {
        contacts.value = [];
        return;
      }

      try {
        const response = await fetch(`/chat/parent/contacts?studentNumber=${selectedChild.value.studentNumber}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          contacts.value = result.data;
          // 如果当前选中的联系人不在新列表中，清除选中
          if (activeContact.value && !contacts.value.some(c => c.userId === activeContact.value.userId)) {
            activeContact.value = null;
            messages.value = [];
          }

          // 加载未读消息数
          await loadUnreadCounts();
        } else {
          error.value = result.msg || '获取联系人失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 选择联系人
    const selectContact = async (contact) => {
      activeContact.value = contact;
      await loadChatHistory();
      scrollToBottom();
      // 标记消息为已读
      await markMessagesAsRead(contact.userId);
      // 开始定时刷新消息
      startMessageRefresh();
    };

    // 加载聊天历史
    const loadChatHistory = async () => {
      if (!activeContact.value) return;

      try {
        const response = await fetch(`/chat/history?contactId=${activeContact.value.userId}&page=0&size=50`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          messages.value = result.data;
          await nextTick();
          scrollToBottom();
        } else {
          error.value = result.msg || '获取聊天记录失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 发送消息
    const sendMessage = async (e) => {
      if (e && e.shiftKey) return; // 允许Shift+Enter换行
      if (e) e.preventDefault(); // 防止表单默认提交

      if (!newMessage.value.trim() || !activeContact.value) return;

      try {
        const response = await fetch(`/chat/send?recipientId=${activeContact.value.userId}&content=${encodeURIComponent(newMessage.value)}`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code === 1) {
          // 添加到消息列表
          messages.value.push(result.data);
          newMessage.value = '';
          await nextTick();
          scrollToBottom();
        } else {
          error.value = result.msg || '发送消息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 标记消息为已读
    const markMessagesAsRead = async (senderId) => {
      try {
        await fetch(`/chat/mark-as-read?senderId=${senderId}`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        // 更新未读计数
        await loadUnreadCounts();
      } catch (err) {
        console.error('标记消息为已读失败:', err);
      }
    };

    // 加载未读消息数
    const loadUnreadCounts = async () => {
      try {
        if (contacts.value.length === 0) return;

        // 获取所有联系人的ID
        const contactIds = contacts.value.map(contact => contact.userId);

        const response = await fetch('/chat/unread-count-by-contacts', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0'
          },
          body: JSON.stringify(contactIds)
        });

        const result = await response.json();
        if (result.code === 1) {
          unreadCounts.value = result.data;
        } else {
          console.error('获取未读消息数失败:', result.msg);
        }
      } catch (err) {
        console.error('获取未读消息数失败:', err);
      }
    };

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    };

    // 开始定时刷新消息
    const startMessageRefresh = () => {
      // 清除之前的定时器
      if (messageRefreshTimer) {
        clearInterval(messageRefreshTimer);
      }

      // 每10秒刷新一次消息
      messageRefreshTimer = setInterval(() => {
        if (activeContact.value) {
          loadChatHistory();
        }
      }, 10000);
    };

    // 开始定时刷新未读消息数
    const startUnreadCountRefresh = () => {
      // 清除之前的定时器
      if (unreadCountTimer) {
        clearInterval(unreadCountTimer);
      }

      // 每30秒刷新一次未读消息数
      unreadCountTimer = setInterval(() => {
        loadUnreadCounts();
      }, 30000);
    };

    // 停止定时刷新消息
    const stopMessageRefresh = () => {
      if (messageRefreshTimer) {
        clearInterval(messageRefreshTimer);
        messageRefreshTimer = null;
      }
    };

    // 停止定时刷新未读消息数
    const stopUnreadCountRefresh = () => {
      if (unreadCountTimer) {
        clearInterval(unreadCountTimer);
        unreadCountTimer = null;
      }
    };

    // 格式化日期时间
    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '';
      const date = new Date(dateTimeString);
      return date.toLocaleString('zh-CN');
    };

    // 获取用户类型文本
    const getUserTypeText = (userType) => {
      switch (userType) {
        case '1': return '老师';
        case '2': return '学生';
        case '3': return '家长';
        default: return '未知';
      }
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
      // 开始定时刷新未读消息数
      startUnreadCountRefresh();
    });

    // 组件卸载时清理定时器
    onUnmounted(() => {
      stopMessageRefresh();
      stopUnreadCountRefresh();
    });

    return {
      userProfile,
      selectedChild,
      contacts,
      activeContact,
      messages,
      newMessage,
      messagesContainer,
      unreadCounts,
      error,
      success,
      loadContacts,
      selectContact,
      loadChatHistory,
      sendMessage,
      formatDateTime,
      getUserTypeText
    };
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info a {
  color: #409EFF;
  text-decoration: none;
  padding: 5px 10px;
  border: 1px solid #409EFF;
  border-radius: 4px;
  transition: all 0.3s;
}

.user-info a:hover {
  background-color: #409EFF;
  color: white;
}

.chat-main {
  display: flex;
  gap: 20px;
  height: 70vh;
}

.contacts-section {
  flex: 1;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.contacts-section h2 {
  margin-top: 0;
}

.child-selector {
  margin-bottom: 20px;
  display: flex;
  align-items: end;
  gap: 10px;
}

.child-selector label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.child-selector select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.child-selector .refresh-btn {
  height: 32px;
  padding: 0 10px;
  background-color: #9E9E9E;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn:hover {
  background-color: #7a7a7a;
}

.contacts-list {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.contact-item:hover {
  background-color: #f5f5f5;
}

.contact-item.active {
  background-color: #e3f2fd;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.contact-info {
  flex: 1;
}

.contact-name {
  font-weight: bold;
}

.contact-type {
  font-size: 12px;
  color: #666;
}

.unread-badge {
  background-color: #f44336;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.no-contacts {
  text-align: center;
  color: #999;
  padding: 20px;
}

.chat-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chat-header h3 {
  margin: 0;
}

.refresh-btn {
  padding: 5px 10px;
  background-color: #9E9E9E;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 10px;
}

.message.sent {
  align-self: flex-end;
  background-color: #409EFF;
  color: white;
}

.message.received {
  align-self: flex-start;
  background-color: #f5f5f5;
}

.message-content {
  margin-bottom: 5px;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  opacity: 0.8;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  height: 60px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}
</style>